package com.hxzy.shop.cachedao;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.hxzy.shop.constant.AuthConstant;
import com.hxzy.shop.constant.RedisConstant;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Service
public class AuthCacheServiceImpl implements AuthCacheService {
    @Resource
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 主店门店端请求用户信息
     */
    private static final String REQUEST_USER= RedisConstant.REQUEST_USER_INFO;

    /**
     * 主店门店端请求用户信息
     */
    private static final String APPLET_USER_INFO= RedisConstant.APPLET_USER_INFO;
    @Override
    public boolean checkAccount(String k, String realToken) {
        Boolean bool = redisTemplate.hasKey(k);
        if (!bool) {
            return false;
        }
        String value = redisTemplate.opsForValue().get(k);
        assert value != null;
        if (!value.equals(realToken)) {
            return false;
        }
        return true;
    }

    @Override
    public void saveUserDto(String token, UserDto userDto) {
        if (ObjectUtil.isEmpty(userDto)||ObjectUtil.isEmpty(token)){
            return;
        }
        String userDtoStr = JSONUtil.toJsonStr(userDto);
        redisTemplate.opsForValue().set(REQUEST_USER+token,userDtoStr,24, TimeUnit.HOURS);
    }

    @Override
    public Boolean renewalAppletUserInfo(String token) {
        if (ObjectUtil.isEmpty(token)){
            return false;
        }
        return redisTemplate.expire(APPLET_USER_INFO+token,24,TimeUnit.HOURS);
    }
}
